const http = require('http');
const url = require('url')
const fs = require('fs');
const path = require('path');
const app = http.createServer((req, res) => {
    let { pathname } = url.parse(req.url, true)
    pathname = path.join(__dirname, pathname)
    fs.stat(pathname, (error, stat) => {
        if (error) {
            res.statusCode = 404
            res.end('not found')
            return
        }
        if (stat.isFile()) {
            fs.readFile(pathname, (error, data) => {
                if (error) throw error;
                res.statusCode = 200
                res.setHeader("Content-type", "text/html;charset=utf-8")
                res.write(data)
                res.end()
            })
        }
        if (stat.isDirectory()) {
            fs.readFile(path.join(pathname, 'index.html'), (error, data) => {
                if (error) res.end('not found')
                res.statusCode = 200
                res.setHeader("Content-type", "text/html;charset=utf-8")
                res.write(data)
                res.end()
            })
        }
    })
})
app.listen(3000, () => {
    console.log('app is running ...')
})